package id.co.shuba.spamobile.task;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.WSException;
import id.co.shuba.spamobile.data.AreaDB;
import id.co.shuba.spamobile.data.BaseDB;
import id.co.shuba.spamobile.data.StandardDB;
import id.co.shuba.spamobile.services.WebServiceHelper;
import id.co.shuba.spamobile.util.Base64;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DownloadTableTask extends
		BaseProgressTask {
	WebServiceHelper _ws;
	SQLiteDatabase _db;	
	String _unit;
	INotify _notify;	

	public DownloadTableTask(WebServiceHelper ws, SQLiteDatabase db, String unit, INotify notify) {
		_ws = ws;
		_db = db;
		_unit = unit;
		_notify = notify;
	}	

	@Override
	protected AsyncTaskResult<Void> doInBackground(Object... params) {
		try {			
			Map<String, Object> properties = new HashMap<String, Object>();			
			String maxDate = AreaDB.getMaxDate(_db, _unit);
			if (maxDate == null) maxDate = "1900-01-01";
			properties.put("aoCode", _unit);
			properties.put("date", maxDate);
			
			publishStatus("Connecting...");
			String result = _ws.Call("GetUserZip", properties).toString();
			publishProgress(20);
			
			publishStatus("Extracting...");
			String strJSON = new String(Base64.decode(result, Base64.GZIP)); 			
			publishProgress(30);			
			
			JSONObject res = new JSONObject(strJSON);
			String error = res.getString("error");
			if (error.length() > 0 && !error.equals("null"))
				throw new WSException(error);
				
			JSONArray jsonArray = res.getJSONArray("result");					
			publishProgress(50);
						
			//String date = BaseDB.getCurrentDateTime();
			String date = BaseDB.getSysDateTime();
			publishStatus("Updating...");
			int length = jsonArray.length();						
			for (int i = 0; i < length; i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				String zip = jsonObject.getString("zip");
				String kodya = jsonObject.getString("kodya");
				String kecamatan = jsonObject.getString("kecamatan");
				String kelurahan = jsonObject.getString("kelurahan");
				
				AreaDB.addPostalCode(_db, zip, kodya, kecamatan, kelurahan, date, _unit);
				
				int progress = (int)(50 + (50f * (((float)i)/length)));
				publishStatus(String.format("Uploading...%d/%d", i, length));
				publishProgress(progress);
			}
			
			publishStatus("Done!");
			publishProgress(0);
			
			return new AsyncTaskResult<Void>((Void) null);
		} catch (WSException we) {
			publishStatus(we.getMessage());
			publishProgress(0);
			return new AsyncTaskResult<Void>(we);
		} catch (Exception e) {
			Log.e("Download", e.getMessage(), e);
			if (e.getMessage().contains("Unable to resolve") || e.getMessage().contains("failed to connect")) {
				publishStatus("Tidak dapat tersambung ke server");
			} else {
				publishStatus(e.getMessage());
			}
			publishProgress(0);
			return new AsyncTaskResult<Void>(e);
		}				
	}
	
	@Override
	protected void onPostExecute(AsyncTaskResult<Void> result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		
		_notify.notifyFinish(result.getError());
	}

	@Override
	public String getTitle() {		
		return "User ZIP";
	}
	
	@Override
	protected void onCancelled(AsyncTaskResult<Void> result) {		
		super.onCancelled(result);
		
		Log.d("DownloadAreaTask", "Task cancelled");
	}
}
